package cn.ydt.ydt.sso.webapi.service.impl;

import cn.ydt.ydt.common.exception.YdtServiceException;
import cn.ydt.ydt.common.resful.StatusCode;
import cn.ydt.ydt.pojo.admin.dto.NetLoginDTO;
import cn.ydt.ydt.pojo.admin.model.Net;
import cn.ydt.ydt.pojo.user.model.User;
import cn.ydt.ydt.sso.service.INetService;
import cn.ydt.ydt.sso.webapi.mapper.admin.AdminMapper;
import io.jsonwebtoken.Header;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class NetServiceImpl implements INetService {

    @Value("${ydt.jwt.secret-key}")
    private String secretKey;

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    AdminMapper adminMapper;


    @Override
    public String netLogin(NetLoginDTO netLoginDTO) {

        String account = netLoginDTO.getAccount();

        Net net = adminMapper.getNetByAccount(account);
        if (net == null){
            throw new YdtServiceException(StatusCode.LOGIN_USER_FALIED,"请输入正确的账号和密码");
        }

        log.info("利用authenticationManager进行登录认证");
        Authentication authentication = new UsernamePasswordAuthenticationToken(
               netLoginDTO.getAccount(),netLoginDTO.getNetPassword());
        Authentication authenticate = authenticationManager.authenticate(authentication);

        log.info("登录认证成功！");
        log.info("保存信息到claims中");
        Map<String,Object> clamis = new HashMap<>();
        clamis.put("account",account);
        clamis.put("netPassword",net.getNetPassword());
        clamis.put("netId",net.getNetId());
        clamis.put("communityId",net.getCommunityId());
        //用于辨别登录对象
        clamis.put("identity",(byte)2);
        log.info("向jwt中写入数据，生成jwt");
        String jwt = Jwts.builder()
                // Header：指定算法与当前数据类型
                // 格式为： { "alg": 算法, "typ": "jwt" }
                .setHeaderParam(Header.CONTENT_TYPE,"HS256")
                .setHeaderParam(Header.TYPE,Header.JWT_TYPE)
                // Payload：通常包含Claims（自定义数据）和过期时间
                .setClaims(clamis)
                .setExpiration(new Date(System.currentTimeMillis()+10*24*60*60*1000))
                // Signature：由算法和密钥（secret key）这2部分组成
                .signWith(SignatureAlgorithm.HS256, secretKey)
                // 打包生成
                .compact();
        log.info("jwt生成完成，返回jwt数据");
        return jwt;
    }
}
